{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "sys.path.append('../utils')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "from aoc import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "YEAR = 2021\n",
    "DAY = 18"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "sample = '''[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]\n",
    "[[[5,[2,8]],4],[5,[[9,9],0]]]\n",
    "[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]\n",
    "[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]\n",
    "[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]]\n",
    "[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]]\n",
    "[[[[5,4],[7,7]],8],[[8,3],8]]\n",
    "[[9,3],[[9,9],[6,[4,9]]]]\n",
    "[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]\n",
    "[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "inp = get_input(YEAR, DAY)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def do_transform(inp):\n",
    "    return list(filter(lambda x: len(x) > 0, inp.split('\\n')))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "sample = do_transform(sample)\n",
    "inp = do_transform(inp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node:\n",
    "    def __init__(self, parent, value):\n",
    "        self.parent = parent\n",
    "        \n",
    "        if type(value) == int:\n",
    "            self.value = value\n",
    "            self.left = None\n",
    "            self.right = None\n",
    "        elif type(value) == list:\n",
    "            self.value = None\n",
    "            self.left = Node(self, value[0])\n",
    "            self.right = Node(self, value[1])\n",
    "        else:\n",
    "            self.value = None\n",
    "            self.left = None\n",
    "            self.right = None\n",
    "            \n",
    "    def __str__(self):\n",
    "        if self.value != None:\n",
    "            return str(self.value)\n",
    "        \n",
    "        return '[' + str(self.left) + ',' + str(self.right) + ']'\n",
    "    \n",
    "    def __add__(a, b):\n",
    "        node = Node(None, None)\n",
    "        node.left = a.copy()\n",
    "        node.right = b.copy()\n",
    "        node.left.parent = node\n",
    "        node.right.parent = node\n",
    "        node.reduce()\n",
    "        return node\n",
    "    \n",
    "    def pred(self):\n",
    "        if self.parent == None:\n",
    "            return None\n",
    "        \n",
    "        if self == self.parent.left:\n",
    "            return self.parent.pred()\n",
    "        \n",
    "        ans = self.parent.left\n",
    "        while ans.right != None:\n",
    "            ans = ans.right\n",
    "        \n",
    "        return ans\n",
    "    \n",
    "    def succ(self):\n",
    "        if self.parent == None:\n",
    "            return None\n",
    "        \n",
    "        if self == self.parent.right:\n",
    "            return self.parent.succ()\n",
    "        \n",
    "        ans = self.parent.right\n",
    "        while ans.left != None:\n",
    "            ans = ans.left\n",
    "        \n",
    "        return ans\n",
    "    \n",
    "    def mag(self):\n",
    "        if self.value != None:\n",
    "            return self.value\n",
    "        \n",
    "        return 3 * self.left.mag() + 2 * self.right.mag()\n",
    "    \n",
    "    def copy(self):\n",
    "        node = Node(None, None)\n",
    "        node.value = self.value\n",
    "        if self.left != None:\n",
    "            node.left = self.left.copy()\n",
    "            node.left.parent = node\n",
    "        if self.right != None:\n",
    "            node.right = self.right.copy()\n",
    "            node.right.parent = node\n",
    "        return node\n",
    "    \n",
    "    def explode(self):\n",
    "        lv = self.left.value\n",
    "        rv = self.right.value\n",
    "                \n",
    "        l = self.pred()\n",
    "        if l != None:\n",
    "            assert(l.value != None)\n",
    "            l.value += lv\n",
    "            \n",
    "        r = self.succ()\n",
    "        if r != None:\n",
    "            assert(r.value != None)\n",
    "            r.value += rv\n",
    "            \n",
    "        self.value = 0\n",
    "        self.left = None\n",
    "        self.right = None\n",
    "        \n",
    "    def split(self):\n",
    "        lv = self.value // 2\n",
    "        rv = self.value - lv\n",
    "        self.value = None\n",
    "        self.left = Node(self, lv)\n",
    "        self.right = Node(self, rv)\n",
    "    \n",
    "    def reduce(self):        \n",
    "        changed = [False]\n",
    "        \n",
    "        def check_explosion(node, depth):\n",
    "            if node == None or changed[0]:\n",
    "                return\n",
    "            \n",
    "            if depth >= 4 and node.left != None and node.left.value != None:\n",
    "                node.explode()\n",
    "                changed[0] = True\n",
    "                return\n",
    "            \n",
    "            check_explosion(node.left, depth + 1)\n",
    "            check_explosion(node.right, depth + 1)\n",
    "            \n",
    "        def check_split(node):\n",
    "            if node == None or changed[0]:\n",
    "                return\n",
    "\n",
    "            if node.value != None and node.value >= 10:\n",
    "                node.split()\n",
    "                changed[0] = True\n",
    "                return\n",
    "\n",
    "            check_split(node.left)\n",
    "            check_split(node.right)\n",
    "            \n",
    "        check_explosion(self, 0)\n",
    "        \n",
    "        if changed[0]:\n",
    "            self.reduce()\n",
    "            return\n",
    "\n",
    "        check_split(self)\n",
    "        \n",
    "        if changed[0]:\n",
    "            self.reduce()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def part1(inp):\n",
    "    nums = [Node(None, json.loads(line)) for line in inp]   \n",
    "    n = len(nums)\n",
    "    ans = nums[0]\n",
    "\n",
    "    for i in range(n - 1):\n",
    "        node = ans + nums[i + 1]\n",
    "        ans = node\n",
    "        \n",
    "    return ans.mag()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4140"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "part1(sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3756"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "part1_ans = part1(inp)\n",
    "part1_ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "submit_answer(part1_ans, YEAR, DAY)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "def part2(inp):\n",
    "    nums = [Node(None, json.loads(line)) for line in inp]   \n",
    "    n = len(nums)\n",
    "    ans = 0\n",
    "\n",
    "    for i in range(n):\n",
    "        for j in range(n):\n",
    "            if i != j:\n",
    "                node = nums[i] + nums[j]\n",
    "                ans = max(ans, node.mag())\n",
    "                        \n",
    "    return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3993"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "part2(sample)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4585"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "part2_ans = part2(inp)\n",
    "part2_ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "submit_answer(part2_ans, YEAR, DAY, level=2)"
   ]
  }
 ],
 "metadata": {
  "@webio": {
   "lastCommId": null,
   "lastKernelId": null
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
